package com.lucy.viewer.onlyoffice.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.lucy.viewer.onlyoffice.entity.Document;
import com.lucy.viewer.onlyoffice.entity.DocumentEditParam;
import com.lucy.viewer.onlyoffice.service.DocumentService;
import com.lucy.viewer.params.ViewerFile;
import com.lucy.viewer.service.ViewerFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author kindear
 *
 */
@Slf4j
@Service
public class DocumentServiceImpl implements DocumentService {



    @Value("${server.host}")
    String serverHost;

    @Autowired(required = true)
    ViewerFileService fileService;


    @Override
    public Document getDocument(String documentKey) {
        // 如果不为空 获取文件信息
        ViewerFile file = fileService.getViewerFile(documentKey);
        Document document = new Document();
        BeanUtil.copyProperties(file,document, CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
        return document;
    }

    @Override
    public void downloadDocumentFile(String documentKey, HttpServletRequest request, HttpServletResponse response) throws IOException {

    }

    @Override
    public DocumentEditParam buildDocumentEditParam(String userId, String userName) {
        return DocumentEditParam.builder()
                .callbackUrl(callbackUrl())
                .user(DocumentEditParam.UserBean.builder()
                        .id(userId)
                        .name(userName)
                        .build())
                .build();
    }

    @Override
    public boolean saveDocumentFile(String documentKey, String downloadUrl) throws IOException {
        // 如果不为空 获取文件信息
        ViewerFile file = fileService.getViewerFile(documentKey);
        Document document = new Document();

        return false;
    }

    private String callbackUrl() {
        return serverHost + "/viewer/onlyoffice/callback";
    }


    @Override
    public Object getServerHost() {
        return serverHost;
    }

    @Override
    public boolean canEdit(Document document) {
        List<String> editList = new ArrayList<>();
        editList.add("doc");
        editList.add("docx");
        editList.add("xls");
        editList.add("xlsx");
        editList.add("ppt");
        editList.add("pptx");
        return editList.contains(document.getFileType());
        //return false;
    }
}
